package com.whately.core.base.controller;

import com.whately.core.base.utils.AESUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class ClientSignUtil {

    private final static String SALT_PRE= "88480721";

    private final static String PREFIX="hitoo";

    public final static String access_key_type_simple = "1";

    public static String geneAkSimple(String timestamp){
        //先把ts
        String keySalt= SALT_PRE+geneSalt(timestamp);
        return geneAk(keySalt,PREFIX,timestamp,access_key_type_simple);
    }

    private static String geneAk(String keySalt  , String... params){
        String str= StringUtils.EMPTY;
        for(String s:params){
            if(str.length()>0){
                str += "-";
            }
            str += s;
        }
        String accessKey= AESUtils.encrypt(keySalt,str);
        return accessKey;
    }

    /**
     *
     * 解密后格式：prefix-timestamp+type
     */
    public static String decodeAk(String timestamp,String data){
        String decryptKey;
        try{
            String keySalt= SALT_PRE+geneSalt(timestamp);
            decryptKey = AESUtils.decrypt(keySalt,data);
            if(decryptKey.indexOf(PREFIX+"-"+timestamp)!=0){
                decryptKey = "";
            }
        }catch (Exception e){
            log.error("ClientSignUtil decodeAk error",e);
            decryptKey = "";
        }
        return decryptKey;
    }

    private static String geneSalt(String timestamp){
        String salt = timestamp.substring(1,9);
        StringBuffer sb = new StringBuffer(salt);
        return sb.reverse().toString();
    }
}
